/*
   This file is part of the 'Let's Do Stuff Together' project
   http://code.google.com/p/dostufftogether/

   Copyright 2010 Christoph Fuchs, Stefan Thaler

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.appspot.android2gather;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.appspot.android2gather.activity.ErrorMessage;
import com.appspot.android2gather.activity.RequestParameters;
import com.appspot.android2gather.configuration.ServerConfiguration;
import com.appspot.android2gather.location.ActivityLocationListener;
import com.appspot.android2gather.location.MyGoogleMaps;
import com.appspot.android2gather.util.QueryHelper;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.google.android.maps.GeoPoint;
import com.google.gson.Gson;

/**
 * 
 * Android activity to create an activity (<i>not</i> an Android activity, but
 * an activity in the sense of something that can be done together, hence the
 * central object of our application) and set it to the activity server.
 * 
 * The activity is created by invoking the REST defined interface. For creating
 * an activity the interface looks as follows
 * 
 * <blockquote>http://example.com/ActivityServer/activity/?title=TITLE&
 * description
 * =PLAIN_TEXT&long=LONGITUDE&lat=LATITUDE&alt=ALTITUDE&startTime=TIMESTAMP
 * &endTime=TIMESTAMP</blockquote>
 * 
 * @author Christoph 'Gigi' Fuchs
 * 
 */
public class CreateActivity extends Activity {

	/** The Constant TIME_DIALOG_ID. */
	private static final int TIME_DIALOG_ID = 0;

	/** The Constant DATE_DIALOG_ID. */
	protected static final int DATE_DIALOG_ID = 1;

	protected static final int MAP_REQUEST_CODE = 1337;

	private TextView mTimeDisplay;
	private ImageButton mPickTime;
	private int mHour;
	private int mMinute;
	private TextView mDateDisplay;
	private ImageButton mPickDate;
	private int mYear;
	private int mMonth;
	private int mDay;
	// private ImageButton mNow;
	// private ImageButton mToday;
	private ImageButton mCurrentPosition;
	private ImageButton mReverseGeocode;
	private ImageButton mMap;
	private LocationManager mlocManager;
	private ActivityLocationListener mlocListener;
	private Location lastKnownLocation;
	private Button mOk;
	private TextView mTitle;
	private TextView mDescripition;
	private CheckBox mPublishOnFacebook;
	private CheckBox mCreateFacebookEvent;
	private RadioGroup mCategory;

	private double mLatitude;

	private double mLongitude;

	private String mAddressName;

	private EditText mAddressField;

	private String mCategoriesList;

	private AlertDialog.Builder alertDialog;

	private String validateMessage;
	
	private CheckBox mNotifiyClosebyFacebookFriends;
	
	private CheckBox mPublishOnbuzz;

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreate(android.os.Bundle)
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.create);

		// Title and description
		mTitle = (TextView) findViewById(R.id.text_createTitle);
		mDescripition = (TextView) findViewById(R.id.text_createDescription);

		// Date and Time related stuff
		createDateTimeListeners();
		setCurrentTimePlusOneHour();
		setCurrentDay();

		// Location related stuff
		mMap = (ImageButton) findViewById(R.id.imagebutton_map);
		mMap.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.i("View", "Switching to Google maps view");
				Intent mapsIntent = new Intent(v.getContext(),
						MyGoogleMaps.class);
				startActivityForResult(mapsIntent, MAP_REQUEST_CODE);
			}
		});
		mAddressField = (EditText) findViewById(R.id.text_create_map_address);
		mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		mlocListener = new ActivityLocationListener();
		mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
				mlocListener);
		lastKnownLocation = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		mCurrentPosition = (ImageButton) findViewById(R.id.imagebutton_location);
		mCurrentPosition.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String addressNameFromGeoCoder = MyGoogleMaps
						.getAddressNameFromGeoCoder(getBaseContext(),
								mlocListener.getLatitude(),
								mlocListener.getLongitude());
				Log.v("GeoCoder", "Got address name for current position: "
						+ addressNameFromGeoCoder);
				mAddressField.setText(addressNameFromGeoCoder);
			}
		});
		
		mPublishOnbuzz = (CheckBox) findViewById(R.id.checkbox_share_on_buzz);

		mReverseGeocode = (ImageButton) findViewById(R.id.imagebutton_create_search);
		mReverseGeocode.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				doGeoCoding();
			}
		});

		mCategory = (RadioGroup) findViewById(R.id.radiogroup_create_categories);

		mPublishOnFacebook = (CheckBox) findViewById(R.id.checkbox_publish_on_facebook);
		mCreateFacebookEvent = (CheckBox) findViewById(R.id.checkbox_create_facebook_event);
		mNotifiyClosebyFacebookFriends = (CheckBox) findViewById(R.id.checkbox_notify_closeby_friends);

		/**
		 * // /* // * Duration //
		 */
		// Spinner s = (Spinner) findViewById(R.id.spinner_createDuration);
		// ArrayAdapter adapter = ArrayAdapter.createFromResource(
		// this, R.array.durations, android.R.layout.simple_spinner_item);
		// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// s.setAdapter(adapter);

		// The OK button
		mOk = (Button) findViewById(R.id.button_create_activity);
		mOk.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.i("View", "Submitting activity to server.");
				if (validateInputs()) {
					doGeoCoding();
					String activityId=null;
					try {
						activityId= submitToServer();
					} catch (URISyntaxException e) {
						Log.e("Create on server", QueryHelper.getStrackTrace(e));
					}
					// TODO if facebook checkbox push on facebook
					
					if(activityId==null)
					{
						Toast.makeText(getApplicationContext(),"Failed to create event.", Toast.LENGTH_LONG);
						return;
					}
					
					if (mPublishOnbuzz.isChecked())
					{
						QueryHelper.shareOnBuzz("Let's get 2Gather! "+mTitle.getText()+" on "+getDateTimeString());
					}
					
					
					if(mCreateFacebookEvent.isChecked()) {
						waitfor++;
					} 
					if (mPublishOnFacebook.isChecked()) {
						waitfor++;
					}
					
					if (mNotifiyClosebyFacebookFriends.isChecked()) {
						waitfor++;
					}
					
					
					if(mCreateFacebookEvent.isChecked()) {
						tries = 0;
						createFacebookEvent(activityId);
					} 
					if (mPublishOnFacebook.isChecked()) {
						tries = 0;
						publishEventOnFacebook(); // will continue on to home
													// screen after success
					}
					
					if (mNotifiyClosebyFacebookFriends.isChecked()) {
						tries = 0;
						notifyClosebyFacebookFriends(); // will continue on to home
					}
					
					moveHome();

				} else {
					showInvalidFormDialog(validateMessage);
				}

			}

			

		});

		// initialize the a
		initInvalidFormDialog();
		// display the current date
		updateDisplay();
	}

	/**
	 * Publishes the event on facebook.
	 */
	boolean loggedIn = false;
	int tries = 0;
	
	private String getFacebookEventPublishMessage() {
		StringBuffer sb = new StringBuffer();
		
		Calendar  c = new GregorianCalendar();
		c.set(mYear,mMonth, mDay);
		c.set(Calendar.HOUR_OF_DAY, mHour);
		c.set(Calendar.MINUTE, mMinute);
		
		sb.append("Let's meet to "+mDescripition.getText()+". Join us at "+mAddressField.getText()+", "+new Date(c.getTimeInMillis()).toGMTString());
		return sb.toString();

	}
	
	/**
	 * Tries ten time to publish an event on Facebook on the authroized users wall
	 */

	private void publishEventOnFacebook() {
		if (tries >= 10) {
			waitfor--;
			moveHome();
			return;
		}

		Log.i("Create", "Trying to log on on Facebook:" + (tries++)
				+ ". attempt.");
		
		//http://developers.facebook.com/docs/authentication/permissions
		
		
		
		
		
//		LetsDoStuff.facebook.authorize(   LetsDoStuff.letsDoStuff ,ServerConfiguration.permissions, new DialogListener() { 
//
//			@Override
//			public void onComplete(Bundle values) {
				Bundle values = LetsDoStuff.getFBBundle();
				//values.putString("name", "Android2Gather event created!!!");
				values.putString("message", getFacebookEventPublishMessage());
				
				try {
					String response = LetsDoStuff.facebook.request("me/feed",
							values,"POST"); // publish on my wall
					Log.i("FB Create" , response);
				} catch (MalformedURLException e) {
					Log.e("WallPost", QueryHelper.getStrackTrace(e));
				} catch (IOException e) {
					Log.e("WallPost", QueryHelper.getStrackTrace(e));
				}
				
				waitfor--;
				moveHome();

//			}

			

//			@Override
//			public void onFacebookError(FacebookError e) {
//				Log.e("WallPost", QueryHelper.getStrackTrace(e));
//				tries++;
//				publishEventOnFacebook();
//			}
//
//			@Override
//			public void onError(DialogError e) {
//				Log.e("WallPost", QueryHelper.getStrackTrace(e));
//				tries++;
//				publishEventOnFacebook();
//			}
//
//			@Override
//			public void onCancel() {
//				Log.e("WallPost", "Cancelled");
//				waitfor--;
//			}
//
//		});
		

	}
	
	/**
	 * Send a message to facebook friends that are in the surrounding of the created event.
	 */
	private void notifyClosebyFacebookFriends() {
		if (tries >= 10) {
			waitfor--;
			moveHome();
			return;
		}

		Log.i("Create", "Trying to log on on Facebook:" + (tries++)
				+ ". attempt.");
		
		//http://developers.facebook.com/docs/authentication/permissions
//		LetsDoStuff.facebook.authorize(   LetsDoStuff.letsDoStuff ,ServerConfiguration.permissions, new DialogListener() { 
//
//			@Override
//			public void onComplete(final Bundle values) {
				
				//values.putString("name", "Android2Gather event created!!!");
				//values.putString("message", getFacebookEventPublishMessage());
				
				
				String accessToken = LetsDoStuff.facebook.getAccessToken();
				Log.i("FACEBOOK",accessToken);
				List<NameValuePair> queryParams = new ArrayList<NameValuePair>();

				queryParams.add(new BasicNameValuePair("type", "checkin"));
				queryParams.add(new BasicNameValuePair("access_token", accessToken));

				URI requestUri;
				try {
					requestUri = URIUtils.createURI("https", "graph.facebook.com",
							-1, "/search", URLEncodedUtils.format(queryParams, "UTF-8"),
							null);
					String responseJSON = QueryHelper.queryServer(getApplicationContext() , requestUri);
					GeoPoint eventLocation = new GeoPoint((int)(mLatitude* 1E6) ,(int) (mLongitude* 1E6));
					CheckinResponseData fromJson = new Gson().fromJson(responseJSON , CheckinResponseData.class);
					for (final CheckinResponse c: fromJson.getData()) 
					{
						FBLocation loc = c.getPlace().getLocation();  
						Double latitude = Double.parseDouble(loc.getLatitude());
						Double longitude = Double.parseDouble(loc.getLongitude());
						GeoPoint friendLocation = new GeoPoint((int)(latitude*1E6), (int)(longitude*1E6));
						double distance = getDistance(eventLocation,friendLocation);
						Log.v("Checkins", c.getFrom().getName()+" distance to event:"+distance);
						
						if (distance<ServerConfiguration.DEFAULT_RANGE/1000) 
						{//activity within range, post on this users wall
							//post on this users wall
							//http://developers.facebook.com/docs/authentication/permissions
							Bundle values2 = LetsDoStuff.getFBBundle();
							
							values2.putString("message", getFacebookEventPublishMessage());
								String response;
								try {
									response = LetsDoStuff.facebook.request(c.getFrom().getId()+"/feed",
											values2,"POST");
									Log.i("Post on "+c.getFrom().getId()+"s wall:" , response);
									
								} catch (Exception e) {
									Log.e("Location",QueryHelper.getStrackTrace(e));
								} // publish on my wall
								
							
							
							
							
						}
						
					}
					
					
					Log.v("Checkins", responseJSON+"");
				} catch (Exception e) {
					Log.e("Checkins",QueryHelper.getStrackTrace(e));
				}
				
//				waitfor--;
//				moveHome();

//			}

			

//			@Override
//			public void onFacebookError(FacebookError e) {
//				Log.e("WallPost", QueryHelper.getStrackTrace(e));
//				tries++;
//				publishEventOnFacebook();
//			}

//			@Override
//			public void onError(DialogError e) {
//				Log.e("WallPost", QueryHelper.getStrackTrace(e));
//				tries++;
//				publishEventOnFacebook();
//			}

//			@Override
//			public void onCancel() {
//				Log.e("WallPost", "Cancelled");
//				waitfor--;
//			}
//
//		});
		
	}
	
	public static final Double Radius = 6384.4d; 
	
	/**
	 * Returns the distance between two geopoints in km
	 * @param StartP
	 * @param EndP
	 * @return
	 */
	 public static double getDistance(GeoPoint StartP, GeoPoint EndP) {
	      double lat1 = StartP.getLatitudeE6()/1E6;
	      double lat2 = EndP.getLatitudeE6()/1E6;
	      double lon1 = StartP.getLongitudeE6()/1E6;
	      double lon2 = EndP.getLongitudeE6()/1E6;
	      double dLat = Math.toRadians(lat2-lat1);
	      double dLon = Math.toRadians(lon2-lon1);
	      double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
	      Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * 
	      Math.sin(dLon/2) * Math.sin(dLon/2); 
	      double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
	      return Radius * c;
	   }
	
	int waitfor=0;
	
	public void moveHome() 
	{
//		Log.i("WaitFor",waitfor+"");
//		if (waitfor<=0)
//		{
			// move to home screen
			Intent homeScreen = new Intent(getApplicationContext(),
					LetsDoStuff.class);
			startActivity(homeScreen);
//		}
		
	}
	
	/**
	 * Creates a Facebook Event from the Activity data. Tries 10 times.
	 * @param activityId 
	 */
	protected void createFacebookEvent(final String activityId) {
		Toast.makeText(getApplicationContext(), "create facebook event", Toast.LENGTH_SHORT);
		
		if (tries >= 10) {
			waitfor--;
			moveHome();
			return;
		}

		Log.i("Facebook Event", "Trying to log on on Facebook:" + (tries++)
				+ ". attempt.");
		
		//http://developers.facebook.com/docs/authentication/permissions
//		
//		LetsDoStuff.facebook.authorize(   LetsDoStuff.letsDoStuff ,ServerConfiguration.permissions, new DialogListener() { 
//
//			@Override
//			public void onComplete(Bundle values) {
				/*
				 * Build our bundle of attributes for the event to be created
				 */
				//compulsory
				Log.v("Create", mYear+" " + " " + mMonth + " " +mDay+" "+mHour+" "+mMinute+" "+System.currentTimeMillis()); 

				Calendar  c = new GregorianCalendar();
				c.set(mYear,mMonth, mDay);
				c.set(Calendar.HOUR_OF_DAY, mHour);
				c.set(Calendar.MINUTE, mMinute);
				Bundle values = LetsDoStuff.getFBBundle();
				values.putString("name", mTitle.getText().toString());				
				values.putString("start_time", (c.getTimeInMillis()/1000)+"");
				values.putString("end_time",  ((c.getTimeInMillis()+3600*1000)/1000)+"");
				//optional
				values.putString("location", mAddressField.getText().toString());
				values.putString("description", mDescripition.getText().toString());
				values.putString("privacy", "OPEN");
				
				try {					
					String response = LetsDoStuff.facebook.request("me/events",
							values,"POST"); // publish on my events
					CreateFacebookEventResponse fbesponse = new Gson().fromJson(response, CreateFacebookEventResponse.class);
					
					addFBIdtoActivity(activityId, fbesponse.getId());
					if (fbesponse.getId()!=null) 
					{
						Toast.makeText(getApplicationContext(), "FacebookEvent "+fbesponse.getId()+ "  created.",Toast.LENGTH_SHORT);
					}
					
					
					Log.i("Facebook Event Create" , response);
					
					
					
				} catch (MalformedURLException e) {
					Log.e("Facebook Event", QueryHelper.getStrackTrace(e));
				} catch (IOException e) {
					Log.e("Facebook Event", QueryHelper.getStrackTrace(e));
				}
				
//				waitfor--;
//				moveHome();
//			}
		

			


//			@Override
//			public void onFacebookError(FacebookError e) {
//				Log.e("Facebook Event", QueryHelper.getStrackTrace(e));
//				tries++;
//				createFacebookEvent(activityId);
//			}
//
//			@Override
//			public void onError(DialogError e) {
//				Log.e("Facebook Event", QueryHelper.getStrackTrace(e));
//				tries++;
//				createFacebookEvent(activityId);
//			}
//
//			@Override
//			public void onCancel() {
//				Log.e("Facebook Event", "Cancelled");
//				waitfor--;
//			}
//
//		});
	}
	private void addFBIdtoActivity(String activityId, String facebookEventId) {
		List<NameValuePair> queryParams = new ArrayList<NameValuePair>();
		queryParams.add(new BasicNameValuePair(RequestParameters.ID, activityId
				));
		queryParams.add(new BasicNameValuePair("fbeid",
				facebookEventId));
		queryParams.add(new BasicNameValuePair("m", "post"));

		try {
			URI updateFacebokEventId = URIUtils.createURI("http", ServerConfiguration.ACTIVITY_SERVER,
					-1, "/activity", URLEncodedUtils.format(queryParams, "UTF-8"),
					null);
			QueryHelper.queryServer(getApplicationContext(), updateFacebokEventId);
		} catch (URISyntaxException e) {
		}
		
	}
	
	/**
	 * Builds a date/time string from in the following format:
	 * 22 Jun 1999 13:02:00 GMT
	 * @return the formatted string
	 */
	private String getDateTimeString() {
		Date date = new Date();
		date.setDate(mDay);
		date.setHours(mHour);
		date.setMinutes(mMinute);
		date.setMonth(mMonth);
		date.setYear(mYear);
		return date.toGMTString();
	}

	private void initInvalidFormDialog() {
		alertDialog = new AlertDialog.Builder(this);
		alertDialog.setMessage("").setCancelable(false)
				.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// do nothing
					}
				});
	}

	private void showInvalidFormDialog(String message) {
		alertDialog.setMessage(message).create();
		alertDialog.show();

	}

	/**
	 * validates the inputs of the CreateActivity form.
	 * 
	 * @return
	 */
	private boolean validateInputs() {
		// title is required;
		validateMessage = "";
		boolean valid = true;
		if (mTitle.getEditableText().length() == 0) {
			validateMessage += "Please enter a title. \n";
			valid = false;
		}
		if (mDescripition.getEditableText().length() == 0) {
			validateMessage += "Please enter a description. \n";
			valid = false;
		}
		if (!validateTimeAndDay(mYear, mMonth, mDay, mHour, mMinute)) {
			validateMessage += "Your activity has to be scheduled in the future. \n";
			valid = false;
		}
		return valid;
	}

	/**
	 * If the user simply typed in a string, find the according GeoPoint.
	 */
	protected void doGeoCoding() {

		Geocoder geoCoder = new Geocoder(getBaseContext());
		GeoPoint point = null;
		try {
			List<Address> addresses = geoCoder.getFromLocationName(
					mAddressField.getText().toString(), 1);
			if (addresses.size() > 0) {
				point = new GeoPoint(
						(int) (addresses.get(0).getLatitude() * 1E6),
						(int) (addresses.get(0).getLongitude() * 1E6));
				// set addressfield
				String add = "";
				if (addresses.size() > 0) {
					for (int i = 0; i < addresses.get(0)
							.getMaxAddressLineIndex(); i++)
						add += addresses.get(0).getAddressLine(i) + "\n";
				}
				mAddressField.setText(add);
			} else {
				mAddressField.setText("Location not found.");
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.v("GeoCoding", "User typed in " + mAddressField.getText()
				+ ". Got GeoPoint " + point);

		if (point == null) {
			Log.e("GeoCoding", "Unable to geoCode current location.");
			return;
		}

		mLongitude = point.getLongitudeE6() / 1E6;
		mLatitude = point.getLatitudeE6() / 1E6;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		Log.v("Create", "onActivityResult fired with request code "
				+ requestCode + " and result code " + resultCode);

		switch (requestCode) {
		case (MAP_REQUEST_CODE): {
			if (resultCode == Activity.RESULT_OK) {
				Log.v("Create", "Retrieving GeoLocation from Map");
				mLatitude = data.getIntExtra(MyGoogleMaps.GEO_LATITUDE_E6, 0) / 1E6;
				mLongitude = data.getIntExtra(MyGoogleMaps.GEO_LONGITUDE_E6, 0) / 1E6;
				mAddressName = data.getStringExtra(MyGoogleMaps.GEO_ADDRESS);
				mAddressField.setText(mAddressName);

				Log.v("Create", "Longitude: " + mLongitude + ", Latitude: "
						+ mLatitude + ", Address Name: " + mAddressName);

			}
			break;
		}
		}
	}

	/**
	 * Creates the date and time listeners.
	 */
	private void createDateTimeListeners() {
		// capture our View elements (time and date)
		mTimeDisplay = (TextView) findViewById(R.id.label_timeDisplay);
		mPickTime = (ImageButton) findViewById(R.id.button_pickTime);

		mDateDisplay = (TextView) findViewById(R.id.label_dateDisplay);
		mPickDate = (ImageButton) findViewById(R.id.button_pickDate);

		// add a click listener to the buttons
		mPickTime.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(TIME_DIALOG_ID);
			}
		});

		mPickDate.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});

	}

	/**
	 * Sets the current time.
	 */
	private void setCurrentTimePlusOneHour() {
		// get the current time
		final Calendar c = Calendar.getInstance();
		mHour = c.get(Calendar.HOUR_OF_DAY) + 1;
		if (mHour == 24)
			mHour = 0;
		mMinute = c.get(Calendar.MINUTE);
	}

	/**
	 * Sets the current day.
	 */
	private void setCurrentDay() {
		// get the current date
		final Calendar c = Calendar.getInstance();
		mYear = c.get(Calendar.YEAR);
		mMonth = c.get(Calendar.MONTH);
		mDay = c.get(Calendar.DAY_OF_MONTH);
		Log.v("Create", mYear+" " + " " + mMonth + " " +mDay); 
	}

	/**
	 * Submit the activity to the server so he can create and store it. Using
	 * HTTP POST.
	 * 
	 * @throws URISyntaxException
	 */
	private String submitToServer() throws URISyntaxException {
		String response = QueryHelper.queryServer(getBaseContext(),
				getRequestUri());

		if (! "false".equals(response)) {
			Toast toast = Toast.makeText(this.getApplicationContext(),
					"Successfully created Activity", Toast.LENGTH_LONG);
			toast.show();
			return response;
		} else {
			try {
				ErrorMessage fromJson = new Gson().fromJson(response,
						ErrorMessage.class);
				Toast toast = Toast.makeText(this.getApplicationContext(),
						"A server error occurred:" + fromJson.getM(),
						Toast.LENGTH_SHORT);
				toast.show();
				Log.e("Create", "A server error occurred:" + fromJson.getM());
			} catch (Exception e) {
				Log.e("Create",
						"Wrong response:" + QueryHelper.getStrackTrace(e));
			}
		}
		return null;

	}

	/**
	 * Build a URL used in a HTTP request to create an activity. For the REST
	 * protocol specification see the REST interace specification document.
	 * 
	 * @return the build string
	 * @throws URISyntaxException
	 * @see RequestParameters
	 */
	private URI getRequestUri() throws URISyntaxException {

		List<NameValuePair> queryParams = new ArrayList<NameValuePair>();
		Calendar  c = new GregorianCalendar();
		c.set(mYear,mMonth, mDay);
		c.set(Calendar.HOUR_OF_DAY, mHour);
		c.set(Calendar.MINUTE, mMinute);
		long startTime  = c.getTimeInMillis();
		long endTime  = startTime+1000*3600*5;

		queryParams.add(new BasicNameValuePair(RequestParameters.NAME, mTitle
				.getText().toString()));
		queryParams.add(new BasicNameValuePair(RequestParameters.DESCRIPTION,
				mDescripition.getText().toString()));
		queryParams.add(new BasicNameValuePair(RequestParameters.LONGITUDE,
				mLongitude + ""));
		queryParams.add(new BasicNameValuePair(RequestParameters.LATITUDE,
				mLatitude + ""));
		queryParams.add(new BasicNameValuePair(RequestParameters.STARTTIME, ""
				+ startTime));
		queryParams.add(new BasicNameValuePair(RequestParameters.ENDTIME, ""
				+ endTime));

		Log.e("Create", mCategory.getCheckedRadioButtonId() + "");

		RadioButton selectedCategory = null;

		for (int i = 0; i < mCategory.getChildCount(); i++) {
			if (((RadioButton) mCategory.getChildAt(i)).isChecked()) {
				selectedCategory = (RadioButton) mCategory.getChildAt(i);
			}
		}
		queryParams.add(new BasicNameValuePair(RequestParameters.CATEGORYLIST,
				selectedCategory.getTag().toString()));
		queryParams.add(new BasicNameValuePair("m", "post"));

		return URIUtils.createURI("http", ServerConfiguration.ACTIVITY_SERVER,
				-1, "/activity", URLEncodedUtils.format(queryParams, "UTF-8"),
				null);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateDialog(int)
	 */
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case TIME_DIALOG_ID:
			return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute,
					false);
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, mYear, mMonth,
					mDay);
		}
		return null;
	}

	private void updateDisplay() {
		mTimeDisplay.setText(new StringBuilder().append(pad(mHour)).append(":")
				.append(pad(mMinute)));

		// month + 1 since jan = 00
		mDateDisplay.setText(new StringBuilder().append(pad(mDay)).append(".")
				.append(pad(mMonth + 1)).append(".").append(mYear));
		
		

	}

	private static String pad(int c) {
		if (c >= 10)
			return String.valueOf(c);
		else
			return "0" + String.valueOf(c);
	}

	private boolean validateTimeAndDay(int year, int month, int day,
			int hourOfDay, int minute) {
		boolean valid = true;
		final Calendar now = Calendar.getInstance();
		Calendar activityTime = Calendar.getInstance();
		activityTime.set(year, month, day, hourOfDay, minute, 0);
		valid = now.compareTo(activityTime) == -1; // otherwise the event starts
													// in the past
		return valid;
	}

	// the callback received when the user "sets" the time in the dialog
	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

			if (validateTimeAndDay(mYear, mMonth, mDay, hourOfDay, minute)) {
				mHour = hourOfDay;
				mMinute = minute;
				updateDisplay();
			} else {
				showInvalidFormDialog("Time and Date have to be in the future :-)");
			}

		}
	};

	// the callback received when the user "sets" the date in the dialog
	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {

			if (validateTimeAndDay(year, monthOfYear, dayOfMonth, mHour,
					mMinute)) {
				mYear = year;
				mMonth = monthOfYear;
				mDay = dayOfMonth;
				updateDisplay();
			} else {
				showInvalidFormDialog("Time and Date have to be in the future :-)");
			}

		}
	};
	
	

}

class CheckinResponseData
{
	private CheckinResponse[] data;

	public void setData(CheckinResponse[] data) {
		this.data = data;
	}

	public CheckinResponse[] getData() {
		return data;
	}
	
}

class CheckinResponse
{
	private String id;
	private Application application;
	private String created_time;
	private Place place;
	private Person from; 
	public void setId(String id) {
		this.id = id;
	}
	public String getId() {
		return id;
	}
	public void setApplication(Application application) {
		this.application = application;
	}
	public Application getApplication() {
		return application;
	}
	public void setCreated_time(String created_time) {
		this.created_time = created_time;
	}
	public String getCreated_time() {
		return created_time;
	}
	public void setPlace(Place place) {
		this.place = place;
	}
	public Place getPlace() {
		return place;
	}
	public void setFrom(Person from) {
		this.from = from;
	}
	public Person getFrom() {
		return from;
	}
}

class Place {
	private String id;
	private String name;
	private FBLocation location;
	public void setId(String id) {
		this.id = id;
	}
	public String getId() {
		return id;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setLocation(FBLocation location) {
		this.location = location;
	}
	public FBLocation getLocation() {
		return location;
	}
}

class FBLocation  
{
	private String latitude;
	private String longitude;
	public void setLatitude(String latitude) {
		this.latitude = latitude;
	}
	public String getLatitude() {
		return latitude;
	}
	public void setLongitude(String longitude) {
		this.longitude = longitude;
	}
	public String getLongitude() {
		return longitude;
	}
}

class Application 
{
	private String id;
	private String name;
	public void setId(String id) {
		this.id = id;
	}
	public String getId() {
		return id;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
}

class Person 
{
	private String id;
	private String name;
	public void setId(String id) {
		this.id = id;
	}
	public String getId() {
		return id;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
}

/**
 * Reponse you should receive from a created FB event.
 * @author stefanthaler
 *
 */
class CreateFacebookEventResponse
{
	private String id;

	public void setId(String id) {
		this.id = id;
	}

	public String getId() {
		return id;
	}
}